package com.rickpan.controller;

import com.rickpan.dto.common.ApiResponse;
import com.rickpan.dto.request.ReportManageRequest;
import com.rickpan.dto.response.ReportManageResponse;
import com.rickpan.service.ReportManageService;
import com.rickpan.utils.SecurityUtils;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.validation.Valid;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * 报告管理控制器
 * 提供报告的查询、编辑、删除、导出等管理功能
 */
@RestController
@RequestMapping("/api/work-reports/manage")
@Tag(name = "报告管理", description = "AI生成报告的管理相关接口")
public class ReportManageController {

    private static final Logger logger = LoggerFactory.getLogger(ReportManageController.class);

    @Autowired
    private ReportManageService reportManageService;

    /**
     * 获取报告列表（分页、筛选、搜索）
     */
    @GetMapping("/reports")
    @Operation(summary = "获取报告列表", description = "分页查询用户的AI生成报告，支持筛选和搜索")
    public ApiResponse<Page<ReportManageResponse.ReportSummaryResponse>> getReportList(
            @Parameter(description = "页码，从0开始") @RequestParam(defaultValue = "0") Integer page,
            @Parameter(description = "每页大小") @RequestParam(defaultValue = "10") Integer size,
            @Parameter(description = "报告类型") @RequestParam(required = false) String type,
            @Parameter(description = "报告状态") @RequestParam(required = false) String status,
            @Parameter(description = "搜索关键词") @RequestParam(required = false) String keyword,
            @Parameter(description = "开始日期") @RequestParam(required = false) String startDate,
            @Parameter(description = "结束日期") @RequestParam(required = false) String endDate,
            @Parameter(description = "排序字段") @RequestParam(defaultValue = "createdAt") String sortBy,
            @Parameter(description = "排序方向") @RequestParam(defaultValue = "DESC") String sortDirection) {

        try {
            Long userId = SecurityUtils.getCurrentUserId();
            
            // 构建查询请求
            ReportManageRequest.ReportQueryRequest request = new ReportManageRequest.ReportQueryRequest();
            request.setPage(page);
            request.setSize(size);
            request.setKeyword(keyword);
            request.setSortBy(sortBy);
            request.setSortDirection(sortDirection);
            
            // 设置类型筛选
            if (type != null && !type.trim().isEmpty()) {
                try {
                    request.setType(com.rickpan.entity.GeneratedReport.ReportType.valueOf(type.toUpperCase()));
                } catch (IllegalArgumentException e) {
                    return ApiResponse.error("无效的报告类型: " + type);
                }
            }
            
            // 设置状态筛选
            if (status != null && !status.trim().isEmpty()) {
                try {
                    request.setStatus(com.rickpan.entity.GeneratedReport.ReportStatus.valueOf(status.toUpperCase()));
                } catch (IllegalArgumentException e) {
                    return ApiResponse.error("无效的报告状态: " + status);
                }
            }
            
            // 设置日期范围
            if (startDate != null && !startDate.trim().isEmpty()) {
                try {
                    request.setStartDate(java.time.LocalDate.parse(startDate));
                } catch (Exception e) {
                    return ApiResponse.error("无效的开始日期格式: " + startDate);
                }
            }
            
            if (endDate != null && !endDate.trim().isEmpty()) {
                try {
                    request.setEndDate(java.time.LocalDate.parse(endDate));
                } catch (Exception e) {
                    return ApiResponse.error("无效的结束日期格式: " + endDate);
                }
            }

            Page<ReportManageResponse.ReportSummaryResponse> result = reportManageService.getReportList(userId, request);
            return ApiResponse.success(result);

        } catch (Exception e) {
            logger.error("获取报告列表失败", e);
            return ApiResponse.error("获取报告列表失败: " + e.getMessage());
        }
    }

    /**
     * 获取报告详情
     */
    @GetMapping("/reports/{id}")
    @Operation(summary = "获取报告详情", description = "获取指定报告的详细信息")
    public ApiResponse<ReportManageResponse.ReportDetailResponse> getReportDetail(
            @Parameter(description = "报告ID") @PathVariable Long id) {

        try {
            Long userId = SecurityUtils.getCurrentUserId();
            ReportManageResponse.ReportDetailResponse result = reportManageService.getReportDetail(userId, id);
            return ApiResponse.success(result);

        } catch (Exception e) {
            logger.error("获取报告详情失败，报告ID: {}", id, e);
            return ApiResponse.error("获取报告详情失败: " + e.getMessage());
        }
    }

    /**
     * 更新报告
     */
    @PutMapping("/reports/{id}")
    @Operation(summary = "更新报告", description = "更新报告的标题、内容、状态等信息")
    public ApiResponse<ReportManageResponse.ReportDetailResponse> updateReport(
            @Parameter(description = "报告ID") @PathVariable Long id,
            @Valid @RequestBody ReportManageRequest.ReportUpdateRequest request) {

        try {
            Long userId = SecurityUtils.getCurrentUserId();
            ReportManageResponse.ReportDetailResponse result = reportManageService.updateReport(userId, id, request);
            return ApiResponse.success(result);

        } catch (Exception e) {
            logger.error("更新报告失败，报告ID: {}", id, e);
            return ApiResponse.error("更新报告失败: " + e.getMessage());
        }
    }

    /**
     * 删除报告
     */
    @DeleteMapping("/reports/{id}")
    @Operation(summary = "删除报告", description = "删除指定的报告")
    public ApiResponse<Void> deleteReport(
            @Parameter(description = "报告ID") @PathVariable Long id) {

        try {
            Long userId = SecurityUtils.getCurrentUserId();
            reportManageService.deleteReport(userId, id);
            return ApiResponse.<Void>success("报告删除成功");

        } catch (Exception e) {
            logger.error("删除报告失败，报告ID: {}", id, e);
            return ApiResponse.error("删除报告失败: " + e.getMessage());
        }
    }

    /**
     * 批量删除报告
     */
    @PostMapping("/reports/batch-delete")
    @Operation(summary = "批量删除报告", description = "批量删除多个报告")
    public ApiResponse<Void> batchDeleteReports(
            @Valid @RequestBody ReportManageRequest.BatchOperationRequest request) {

        try {
            Long userId = SecurityUtils.getCurrentUserId();
            
            if (!"DELETE".equalsIgnoreCase(request.getOperation())) {
                return ApiResponse.error("不支持的操作类型: " + request.getOperation());
            }
            
            reportManageService.batchDeleteReports(userId, request.getReportIds());
            return ApiResponse.<Void>success("批量删除成功");

        } catch (Exception e) {
            logger.error("批量删除报告失败", e);
            return ApiResponse.error("批量删除报告失败: " + e.getMessage());
        }
    }

    /**
     * 获取报告统计信息
     */
    @GetMapping("/stats")
    @Operation(summary = "获取报告统计", description = "获取用户报告的统计信息和趋势数据")
    public ApiResponse<ReportManageResponse.ReportStatsResponse> getReportStats() {

        try {
            Long userId = SecurityUtils.getCurrentUserId();
            ReportManageResponse.ReportStatsResponse result = reportManageService.getReportStats(userId);
            return ApiResponse.success(result);

        } catch (Exception e) {
            logger.error("获取报告统计失败", e);
            return ApiResponse.error("获取报告统计失败: " + e.getMessage());
        }
    }

    /**
     * 导出报告（预留接口）
     */
    @GetMapping("/reports/{id}/export")
    @Operation(summary = "导出报告", description = "导出报告为指定格式（PDF、Word、Markdown）")
    public ApiResponse<String> exportReport(
            @Parameter(description = "报告ID") @PathVariable Long id,
            @Parameter(description = "导出格式") @RequestParam(defaultValue = "PDF") String format,
            @Parameter(description = "是否包含原始内容") @RequestParam(defaultValue = "false") Boolean includeOriginal) {

        try {
            Long userId = SecurityUtils.getCurrentUserId();
            
            // 验证格式
            if (!List.of("PDF", "WORD", "MARKDOWN").contains(format.toUpperCase())) {
                return ApiResponse.error("不支持的导出格式: " + format);
            }
            
            // 获取报告详情
            ReportManageResponse.ReportDetailResponse report = reportManageService.getReportDetail(userId, id);
            
            // TODO: 实现具体的导出逻辑
            // 这里先返回一个占位响应，后续可以扩展实现PDF、Word等格式的导出
            String exportContent = includeOriginal ? report.getOriginalContent() : report.getCurrentContent();
            
            ApiResponse<String> response = new ApiResponse<>(200, "导出成功", exportContent);
            return response;

        } catch (Exception e) {
            logger.error("导出报告失败，报告ID: {}", id, e);
            return ApiResponse.error("导出报告失败: " + e.getMessage());
        }
    }
}
